package com.sky.service.impl;


import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description TODO
 * @Author itheima
 * @Date 2023-07-30 11:37
 */
@Service
@Slf4j
public class ReportServiceImpImpl implements ReportService {


    @Autowired

    private OrdersMapper ordersMapper;

    /**
     * 营业额统计接口
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getturnoverStatistics(LocalDate begin, LocalDate end) {
        //定义一个集合存储每一天的数据
        List<LocalDate> dateList = getLocalDates(begin, end);
        List<Double> turnoverList = new ArrayList<>();
        //遍历list集合拿到每一天的集合列表
        for (LocalDate localDate : dateList) {
            //求每天的最大时间和最小时间
            LocalDateTime endtime = LocalDateTime.of(localDate, LocalTime.MAX);
            LocalDateTime bingtime = LocalDateTime.of(localDate, LocalTime.MIN);
            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("begin", bingtime);
            map.put("end", endtime);
            //查找每一天的营业额
            Double countAmount = ordersMapper.getByCountAmount(map);
            //安全判断 因为有可能当天营业额为null
            countAmount = countAmount == null ? 0.0 : countAmount;
            turnoverList.add(countAmount);
        }
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    /**
     * 获取日期列表
     *
     * @param begin
     * @param end
     * @return
     */
    private static List<LocalDate> getLocalDates(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        //定义一个循环 从开始时间开始每次加一天,当到最后一天 结束循环
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            //将数据存入集合
            dateList.add(begin);
        }
        return dateList;
    }

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户统计接口
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getuserStatistics(LocalDate begin, LocalDate end) {
        //得到日期列表
        List<LocalDate> dateList = getLocalDates(begin, end);
        //新增用户数
        List<Integer> newUserList = new ArrayList<>();
        //总用户数
        List<Integer> totalUserList = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            //求每天的最大时间和最小时间
            Map map = geOrdermap(null, localDate);

            //根据方法得到新增用户列表
            Integer userCount = userMapper.countByMap(map);
            newUserList.add(userCount);
            map.put("begin", null);
            //得到总数列表
            Integer userCount1 = userMapper.countByMap(map);
            totalUserList.add(userCount1);
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }


    /**
     * 根据时间区间统计用户数量
     *
     * @param beginTime
     * @param endTime
     * @return
     */
    /*public Integer getUserCount(LocalDateTime beginTime, LocalDateTime endTime) {
        Map map = new HashMap();
        map.put("begin", beginTime);
        map.put("end", endTime);
        return userMapper.countByMap(map);
    }*/

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getordersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getLocalDates(begin, end);
        //每天订单总数集合
        List<Integer> orderCountList = new ArrayList<>();
        //每天有效订单数集合
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            //求每天的最大时间和最小时间
            Map map = geOrdermap(null, localDate);
            //每天订单数
            Integer orderCount = ordersMapper.getBycountOrder(map);
            orderCountList.add(orderCount);
            map = geOrdermap(Orders.COMPLETED, localDate);
            //每天有效订单数
            Integer validOrderCount = ordersMapper.getBycountOrder(map);
            validOrderCountList.add(validOrderCount);
        }
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();

        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 获取每天最大最小时间与订单状态的集合
     *
     * @param status
     * @param localDate
     * @return
     */
    public Map geOrdermap(Integer status, LocalDate localDate) {
        LocalDateTime endtime = LocalDateTime.of(localDate, LocalTime.MAX);
        LocalDateTime bingtime = LocalDateTime.of(localDate, LocalTime.MIN);
        Map map = new HashMap();
        map.put("status", status);
        map.put("begin", bingtime);
        map.put("end", endtime);
        return map;
    }

    /**
     * 查询销量top10接口
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getReportTop10(LocalDate begin, LocalDate end) {
        //开始时间结束时间的最大最小值
        LocalDateTime endtime = LocalDateTime.of(end, LocalTime.MAX);
        LocalDateTime beingtime = LocalDateTime.of(begin, LocalTime.MIN);
        //拿到封装商品销量与名字的实体类的集合
        List<GoodsSalesDTO> goodsSalesDTOList = ordersMapper.getNameAndNUmber(endtime, beingtime, Orders.COMPLETED);
        String nameList = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList()), ",");
        String numberList = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList()), ",");
        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 导出报表接口
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //当前日期
        LocalDate now = LocalDate.now();
        LocalDate localDate = now.plusDays(-30);
        //最小时间
        LocalDateTime begin = LocalDateTime.of(localDate, LocalTime.MIN);
        LocalDate localDate1 = now.plusDays(-1);
        //最大时间
        LocalDateTime end = LocalDateTime.of(localDate1, LocalTime.MAX);
        //获取报表的详细数据
        BusinessDataVO businessData = workspaceService.getBusinessData(begin, end);

        //3.读取模板文件"template/运营数据报表模板.xlsx"的输入流
        //  this.getClass().getClassLoader().getResourceAsStream(路径)  读取运行位置（部署位置）的类路径下的资源
        InputStream resourceAsStream = this.getClass().getClassLoader()
                .getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //根据提供好的模版来创造一个新的Excel模版对象
            XSSFWorkbook workbook = new XSSFWorkbook(resourceAsStream);
            //5.获取里面下标0的工作表对象
            XSSFSheet sheet = workbook.getSheetAt(0);
            //6.1 填充行下标为1单元格下标为1的数据，格式“时间：开始日期至结束日期”
            sheet.getRow(1).getCell(1).setCellValue("时间：" + begin.toString() + "至" + end.toString());
            //6.2 填充行下标为3单元格下标为2的营业额数据
            sheet.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
            //6.2 填充行下标为3单元格下标为4的订单完成率
            sheet.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
            //6.2 填充行下标为3单元格下标为6的新增用户数
            sheet.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
            //6.2 填充行下标为4单元格下标为2的有效订单数
            sheet.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
            //6.2 填充行下标为4单元格下标为4的平均客单价
            sheet.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());
            //填充详细数据
            LocalDate data = localDate;
            for (int i = 0; i < 30; i++) {
                //因为当天是不需要加一的
                if (i != 0) {
                    data = data.plusDays(1);
                }
                BusinessDataVO businessData1 = workspaceService.getBusinessData(LocalDateTime.of(data, LocalTime.MIN),
                        LocalDateTime.of(data, LocalTime.MAX));
                XSSFRow row = sheet.getRow(i + 7);
                row.getCell(1).setCellValue(data.toString());
                //当前行单元格下标2设置营业额
                row.getCell(2).setCellValue(businessData1.getTurnover());
                //当前行单元格下标3设置有效订单数
                row.getCell(3).setCellValue(businessData1.getValidOrderCount());
                //当前行单元格下标4设置订单完成率
                row.getCell(4).setCellValue(businessData1.getOrderCompletionRate());
                //当前行单元格下标5设置平均客单价
                row.getCell(5).setCellValue(businessData1.getUnitPrice());
                //当前行单元格下标6设置新增用户数
                row.getCell(6).setCellValue(businessData1.getNewUsers());
                //8.使用response获取浏览器输出流
                ServletOutputStream outputStream = response.getOutputStream();

                //9.将内存中的excel文件对象输出到浏览器输出流
                workbook.write(outputStream);

                //10.关闭资源
                workbook.close();
                outputStream.close();

            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error("导出报表错误", e.getMessage());
        }
    }

    /**
     * 导出运营数据文件方法
     *
     * @param response
     */
    @Override
    public void export(HttpServletResponse response) {

        try {
            //1.获取近30的的开始日期和结束日期
            LocalDate begin = LocalDate.now().minusDays(30);
            LocalDate end = LocalDate.now().minusDays(1);

            //2.根据开始日期最小时间和结束日期最大时间查询近30天的营业运营数据（30天概览数据）
            LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
            BusinessDataVO businessData = workspaceService.getBusinessData(beginTime, endTime);

            //3.读取模板文件"template/运营数据报表模板.xlsx"的输入流
            //  this.getClass().getClassLoader().getResourceAsStream(路径)  读取运行位置（部署位置）的类路径下的资源
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

            //4.根据上面模板文件输入流创建excel文件对象工作簿
            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);

            //5.获取里面下标0的工作表对象
            XSSFSheet sheet = workbook.getSheetAt(0);

            //6.填充概览数据
            //6.1 填充行下标为1单元格下标为1的数据，格式“时间：开始日期至结束日期”
            sheet.getRow(1).getCell(1).setCellValue("时间：" + begin.toString() + "至" + end.toString());
            //6.2 填充行下标为3单元格下标为2的营业额数据
            sheet.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
            //6.2 填充行下标为3单元格下标为4的订单完成率
            sheet.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
            //6.2 填充行下标为3单元格下标为6的新增用户数
            sheet.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
            //6.2 填充行下标为4单元格下标为2的有效订单数
            sheet.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
            //6.2 填充行下标为4单元格下标为4的平均客单价
            sheet.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());

            //7.填充明细数据
            LocalDate date = begin;
            for (int i = 0; i < 30; i++) {

                //7.1 循环30次
                //7.2 计算获取当天的日期
                if (i != 0) {
                    date = date.plusDays(1);
                }
                //7.3 获取当天的运营数据
                BusinessDataVO businessDataByDay = workspaceService.getBusinessData(
                        LocalDateTime.of(date, LocalTime.MIN),
                        LocalDateTime.of(date, LocalTime.MAX)
                );
                //7.4 填充每一日明细数据
                //获取每一行对象
                XSSFRow row = sheet.getRow(7 + i);
                //当前行单元格下标1设置日期
                row.getCell(1).setCellValue(date.toString());
                //当前行单元格下标2设置营业额
                row.getCell(2).setCellValue(businessDataByDay.getTurnover());
                //当前行单元格下标3设置有效订单数
                row.getCell(3).setCellValue(businessDataByDay.getValidOrderCount());
                //当前行单元格下标4设置订单完成率
                row.getCell(4).setCellValue(businessDataByDay.getOrderCompletionRate());
                //当前行单元格下标5设置平均客单价
                row.getCell(5).setCellValue(businessDataByDay.getUnitPrice());
                //当前行单元格下标6设置新增用户数
                row.getCell(6).setCellValue(businessDataByDay.getNewUsers());
            }

            //8.使用response获取浏览器输出流
            ServletOutputStream outputStream = response.getOutputStream();

            //9.将内存中的excel文件对象输出到浏览器输出流
            workbook.write(outputStream);

            //10.关闭资源
            workbook.close();
            outputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
            log.error("导出excel运营数据报表错误：" + e.getMessage());
            try {
                response.getWriter().println("导出excel运营数据报表错误：" + e.getMessage());
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
}